package com.sixmac.police.controller;

import com.sixmac.common.base.BaseController;
import com.sixmac.core.constant.Constant;
import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.plugins.dao.Db;
import com.sixmac.core.plugins.dao.Md;
import com.sixmac.core.toolbox.Paras;
import com.sixmac.core.toolbox.ajax.AjaxResult;
import com.sixmac.core.toolbox.kit.DateKit;
import com.sixmac.core.toolbox.kit.JsonKit;
import com.sixmac.module.AdminUser;
import com.sixmac.module.Landlord;
import com.sixmac.module.Room;
import com.sixmac.platform.service.LandlordService;
import com.sixmac.platform.service.RoomService;
import com.sixmac.user.ExcelUtil;
import com.sixmac.user.ExportUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * AdminRoleController
 * 2018-09-26 11:15:35
 * @author Blade
 */
@Controller
@RequestMapping("/admin/room")
public class AdminRoomController extends BaseController {
	private static String CODE = "room";
	private static String PREFIX = "t_room";
	private static String LIST_SOURCE = "room.list";
	private static String BASE_PATH = "/police/";

	@Autowired
	RoomService service;
	
	@RequestMapping(KEY_MAIN)
	public String index(ModelMap mm) {
		AdminUser user = (AdminUser) getRequest().getSession().getAttribute(Constant.SESSION_ADMIN_USER);
		String areaIds = Db.queryStr("SELECT GROUP_CONCAT(u.areaId) areaId FROM t_admin_user u WHERE FIND_IN_SET( u.id, queryAllChildByOrg ('"+user.getId()+"') )",null);
		String areaIds2 = Db.queryStr("SELECT GROUP_CONCAT(area.areaCode) areaCode from t_region_area area LEFT JOIN t_admin_user u ON u.cityId = area.cityCode WHERE u.id is not null and u.id = "+user.getId(),null);
		String area = null;
		if (areaIds!=null&&areaIds2!=null){
			area = areaIds+","+areaIds2;
		}else if (areaIds!=null&&areaIds2==null){
			area = areaIds;
		}else if (areaIds==null&&areaIds2!=null){
			area =areaIds2;
		}
		String startDate = getParameter("startDate");
		String endDate = getParameter("endDate");
		String name = getParameter("name");
		String mobile = getParameter("mobile");
		String address = getParameter("address");
		Integer status = getParameterToInt("status");
		Paras paras = Paras.create().set("startDate",startDate).set("areaIds",area).set("endDate",endDate).set("name",name).set("mobile",mobile).set("address",address).set("status",status);
		String sql = Md.getSql(LIST_SOURCE,paras);
		Object grid = paginate(sql);
		mm.put("grid",grid);
		return BASE_PATH + "house_list.html";
	}

	@RequestMapping(KEY_ADD)
	public String add(ModelMap mm) {
		mm.put("code", CODE);
		return BASE_PATH + "room_add.html";
	}

	@RequestMapping(KEY_EDIT + "/{id}")
	public String edit(@PathVariable Integer id, ModelMap mm) {
		Room room = service.findById(id);
		mm.put("model", JsonKit.toJson(room));
		mm.put("id", id);
		mm.put("code", CODE);
		return BASE_PATH + "room_edit.html";
	}

	@RequestMapping(KEY_VIEW + "/{id}")
	public String view(@PathVariable Integer id, ModelMap mm) {
		Room room = service.findById(id);
		mm.put("model", JsonKit.toJson(room));
		mm.put("id", id);
		mm.put("code", CODE);
		return BASE_PATH + "room_view.html";
	}


	@RequestMapping("/map")
	public String map(ModelMap mm) {
		mm.put("code", CODE);
		AdminUser user = (AdminUser) getRequest().getSession().getAttribute(Constant.SESSION_ADMIN_USER);
		if(user == null){
			return "/police/login.html";
		}
		String areaIds = Db.queryStr("SELECT GROUP_CONCAT(u.areaId) areaId FROM t_admin_user u WHERE FIND_IN_SET( u.id, queryAllChildByOrg ('"+user.getId()+"') )",null);
		String areaIds2 = Db.queryStr("SELECT GROUP_CONCAT(area.areaCode) areaCode from t_region_area area LEFT JOIN t_admin_user u ON u.cityId = area.cityCode WHERE u.id is not null and u.id = "+user.getId(),null);
		String area = null;
		if (areaIds!=null&&areaIds2!=null){
			area = areaIds+","+areaIds2;
		}else if (areaIds!=null&&areaIds2==null){
			area = areaIds;
		}else if (areaIds==null&&areaIds2!=null){
			area =areaIds2;
		}

		List<Map> rooms = Db.selectList("SELECT u.*,l.`name`,l.mobile,case  when (SELECT count(*) FROM t_contact c where c.roomId = u.id and status = 0)>0 then 1 when (SELECT count(*) FROM t_tenant_room c where c.roomId = u.id and c.approve = 3)>0 then 2 else 3 end `status` from t_room u LEFT JOIN t_landlord l ON u.landlordId = l.id WHERE u.region in("+area+") limit 0,100");
		List<HashMap> maps = new ArrayList<>();
		for (Map room:rooms){
			HashMap<String,Object> map = new HashMap<>();
			map.put("lat",room.get("lng"));
			map.put("lng",room.get("lat"));
			map.put("image",room.get("images"));
			map.put("address",room.get("address"));
			map.put("mobile",room.get("mobile"));
			map.put("state",room.get("status"));
			map.put("host",room.get("name"));
			maps.add(map);
		}
		mm.put("rooms", JsonKit.toJson(maps));
		return BASE_PATH + "map_distribute.html";
	}

	@ResponseBody
	@RequestMapping(KEY_LIST)
	public Object list() {
		Object grid = paginate(LIST_SOURCE);
		return grid;
	}

	@ResponseBody
	@RequestMapping(KEY_SAVE)
	public AjaxResult save() {
		Room room = mapping(PREFIX, Room.class);
		boolean temp = service.save(room);
		if (temp) {
			return success(SAVE_SUCCESS_MSG);
		} else {
			return error(SAVE_FAIL_MSG);
		}
	}

	@ResponseBody
	@RequestMapping(KEY_UPDATE)
	public AjaxResult update() {
		Room room = mapping(PREFIX, Room.class);
		boolean temp = service.update(room);
		if (temp) {
			return success(UPDATE_SUCCESS_MSG);
		} else {
			return error(UPDATE_FAIL_MSG);
		}
	}

	@ResponseBody
	@RequestMapping(KEY_REMOVE)
	public AjaxResult remove(@RequestParam String ids) {
		int cnt = service.deleteByIds(ids);
		if (cnt > 0) {
			return success(DEL_SUCCESS_MSG);
		} else {
			return error(DEL_FAIL_MSG);
		}
	}

	@RequestMapping("/export")
	public void exportOrderList(String ids, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String excelName = "房屋列表" + DateKit.getDays()+ ".xls";

		try {
			AdminUser user = (AdminUser) getRequest().getSession().getAttribute(Constant.SESSION_ADMIN_USER);
			String areaIds = Db.queryStr("SELECT GROUP_CONCAT(u.areaId) areaId FROM t_admin_user u WHERE FIND_IN_SET( u.id, queryAllChildByOrg ('"+user.getId()+"') )",null);
			String areaIds2 = Db.queryStr("SELECT GROUP_CONCAT(area.areaCode) areaCode from t_region_area area LEFT JOIN t_admin_user u ON u.cityId = area.cityCode WHERE u.id is not null and u.id = "+user.getId(),null);
			String area = null;
			if (areaIds!=null&&areaIds2!=null){
				area = areaIds+","+areaIds2;
			}else if (areaIds!=null&&areaIds2==null){
				area = areaIds;
			}else if (areaIds==null&&areaIds2!=null){
				area =areaIds2;
			}

			String startDate = getParameter("startDate");
			String endDate = getParameter("endDate");
			String name = getParameter("name");
			String mobile = getParameter("mobile");
			String address = getParameter("address");
			Integer status = getParameterToInt("status");
			Paras paras = Paras.create().set("startDate",startDate).set("areaIds",area).set("endDate",endDate).set("name",name).set("mobile",mobile).set("address",address).set("status",status);
			String sql = Md.getSql(LIST_SOURCE,paras);
			if (ids.trim().length()>0){
				sql = "SELECT aa.* from("+sql+")aa where aa.id in("+ids+")";
			}
			List<Map> landlords = Db.selectList(sql);
			List<Map<String,Object>> list = new ArrayList<>();
			for (Map map:landlords) {
				Map<String,Object> hashMap = new HashMap<>();
				hashMap.putAll(map);
				String type = "未入住";
				Integer tenantStatus = Integer.valueOf(map.get("status").toString());
				if (tenantStatus == 1){
					type="已入住";
				}else if(tenantStatus == 2){
					type="已申请";
				}else if(tenantStatus == 3){
					type="未入驻";
				}else{
					type="已退租";
				}

				hashMap.put("statusName",type);
				hashMap.put("createDateName",DateKit.format((Date)(map.get("createDate"))));
				list.add(hashMap);
			}
			ExcelUtil.createExcel(ExportUtil.ROOM_LIST_TEMPLATE, ExportUtil.ROOM_LIST_FIELD, list, ExportUtil.tempFilePath);
			download(request, response, excelName, ExportUtil.tempFilePath);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
